﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._10
{
    public class Leetcode8
    {
        public void Test()
        {
            try
            {
                MyAtoi("+-2");
                MyAtoi("w10734368512");
                MyAtoi("9223372036854775809");
            }
            catch (Exception ex)
            { }
        }
        
        /// 8. String to Integer (atoi)
        /*
         mplement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front. 
             */
        public int MyAtoi(string str)
        {
            str = str.Trim();
            if (str.Length == 0)
                return 0;
            bool hasAddSign = false;
            if (str[0] == '+')
            {
                str = str.Substring(1);
                hasAddSign = true;
            }

            int iRet = 0;

            long tempLong = 0;
            bool isNotEmpty = false;
            for (int i = 0; i < str.Length; i++)
            {
                if (!int.TryParse(str[i].ToString(), out iRet))
                {
                    if (!hasAddSign&&!isNotEmpty && str[i] == '-')
                    {
                        isNotEmpty = true;
                        continue;
                    }

                    if (i == 0)
                        return 0;

                    if (i > 0)
                    {
                        if (int.TryParse(str.Substring(0, i), out iRet))
                        {
                            return iRet;
                        }
                        else
                        { return 0; }
                    }
                }


                tempLong = Convert.ToInt64(str.Substring(0, i + 1));


                if (tempLong > int.MaxValue)
                {
                    return int.MaxValue;
                }

                if (tempLong < int.MinValue)
                {
                    return int.MinValue;
                }

                iRet = (int)tempLong;
            }
            return iRet;
        }
    }
}
